const bcrypt = require('bcryptjs');
const { getUserInfo } = require('../service/user.service')
const {
    userFormateEeeor,
    userAlreadyExited,
    userRegisterError,
    userDoesNotExist,
    userLoginError,
    invalidPassword
} = require('../constant/err.type')
const { fail } = require("../constant");
const userValidator = async (ctx, next) => {
    const {userName, password} = ctx.request.body
    if (!userName || !password) {
        console.error('用户名或者密码为空', ctx.request.body)
        ctx.app.emit('error', userFormateEeeor, ctx)
        return
    }
    await next()
}
const verifyUser = async (ctx, next) => {
    const { userName } = ctx.request.body
    try {
        const res = await getUserInfo({ userName })
        if (res) {
            console.error('用户名已存在', ctx.request.body)
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (err) {
        console.error('获取用户信息错误', err)
        ctx.app.emit('error', userRegisterError,ctx)
        return
    }
    await next()
}
// 密码加密
// bcrypt.compareSync("加密的内容", hash);
const cryptPassword = async (ctx, next) => {
    const {password} = ctx.request.body
    const salt = bcrypt.genSaltSync(10)
    ctx.request.body.password = bcrypt.hashSync(password, salt)
    await next()
}
const verifyLogin = async (ctx, next) => {
    const {userName, password} = ctx.request.body
    // 判断用户是否存在（不存在：报错）
    var res = await getUserInfo({userName})
    if (!res) {
        console.error('用户名不存在', { userName })
        ctx.body = {
            code: fail,
            message: '用户名不存在',
            result: null
        }
        return
    }
    // 密码是否匹配
    if (!bcrypt.compareSync(password, res.password)) {
        ctx.body = {
            code: fail,
            message: '密码无效',
            result: null
        }
        return
    }
    await next()
}

module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}
